<template>
  <div class="wash-appointment">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="searchForm.serviceType" placeholder="请选择" clearable>
            <el-option label="干洗" value="dry_clean" />
            <el-option label="水洗" value="water_wash" />
            <el-option label="熨烫" value="ironing" />
            <el-option label="修补" value="repair" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>预约管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建预约
          </el-button>
        </div>
      </template>
      
      <el-table :data="appointmentList" v-loading="loading" border>
        <el-table-column prop="customerName" label="客户姓名" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="serviceType" label="服务类型">
          <template #default="{ row }">
            {{ getServiceTypeText(row.serviceType) }}
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="预约时间" width="160" />
        <el-table-column prop="address" label="服务地址" min-width="150" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleConfirm(row)" v-if="row.status === 'pending'">
              确认
            </el-button>
            <el-button type="text" @click="handleCancel(row)" v-if="['pending', 'confirmed'].includes(row.status)">
              取消
            </el-button>
            <el-button type="text" @click="handleComplete(row)" v-if="row.status === 'confirmed'">
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="预约详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ currentAppointment.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentAppointment.phone }}</el-descriptions-item>
        <el-descriptions-item label="服务类型">{{ getServiceTypeText(currentAppointment.serviceType) }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ currentAppointment.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="服务地址" :span="2">{{ currentAppointment.address }}</el-descriptions-item>
        <el-descriptions-item label="预约状态">
          <el-tag :type="getStatusType(currentAppointment.status)">
            {{ getStatusText(currentAppointment.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentAppointment.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentAppointment.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新建预约对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新建预约"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="formData.serviceType" placeholder="请选择服务类型" style="width: 100%;">
            <el-option label="干洗" value="dry_clean" />
            <el-option label="水洗" value="water_wash" />
            <el-option label="熨烫" value="ironing" />
            <el-option label="修补" value="repair" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="formData.appointmentTime"
            type="datetime"
            placeholder="请选择预约时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="服务地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入服务地址" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { appointment } from '@/api/wash/index'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formRef = ref()
const appointmentList = ref([])
const currentAppointment = ref({})

// 搜索表单
const searchForm = reactive({
  customerName: '',
  serviceType: '',
  status: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  customerName: '',
  phone: '',
  serviceType: '',
  appointmentTime: '',
  address: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  serviceType: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  appointmentTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  address: [{ required: true, message: '请输入服务地址', trigger: 'blur' }]
}

const getAppointmentList = async () => {
  loading.value = true
  try {
    const res = await getAppointmentListAPI({
      page: page.current,
      size: page.size,
      ...searchForm
    })
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      appointmentList.value = data.records || data.content || data || []
      page.total = data.total || data.totalElements || 0
    } else {
      appointmentList.value = []
      page.total = 0
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.warning('获取预约列表失败，请检查网络连接')
    appointmentList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

const getServiceTypeText = (type) => {
  const typeMap = {
    dry_clean: '干洗',
    water_wash: '水洗',
    ironing: '熨烫',
    repair: '修补'
  }
  return typeMap[type] || type
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'success',
    cancelled: 'danger',
    completed: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待确认',
    confirmed: '已确认',
    cancelled: '已取消',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

const handleSearch = () => {
  page.current = 1
  getAppointmentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    serviceType: '',
    status: ''
  })
  handleSearch()
}

const handleAdd = () => {
  resetFormData()
  dialogVisible.value = true
}

const handleView = (row) => {
  currentAppointment.value = row
  detailDialogVisible.value = true
}

const handleConfirm = async (row) => {
  try {
    const res = await updateAppointmentStatus(row.id, 'confirmed')
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('预约已确认')
      row.status = 'confirmed'
    }
  } catch (error) {
    console.error('确认预约失败:', error)
    ElMessage.error('确认预约失败')
  }
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateAppointmentStatus(row.id, 'cancelled')
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('预约已取消')
      row.status = 'cancelled'
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }
}

const handleComplete = async (row) => {
  try {
    const res = await updateAppointmentStatus(row.id, 'completed')
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('预约已完成')
      row.status = 'completed'
    }
  } catch (error) {
    console.error('完成预约失败:', error)
    ElMessage.error('完成预约失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const res = await createAppointment(formData)
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('预约创建成功')
      dialogVisible.value = false
      getAppointmentList()
    }
  } catch (error) {
    console.error('创建预约失败:', error)
    ElMessage.error('创建预约失败')
  } finally {
    submitLoading.value = false
  }
}

const resetFormData = () => {
  Object.assign(formData, {
    customerName: '',
    phone: '',
    serviceType: '',
    appointmentTime: '',
    address: '',
    remark: ''
  })
}

const handleSizeChange = () => {
  getAppointmentList()
}

const handleCurrentChange = () => {
  getAppointmentList()
}

onMounted(() => {
  getAppointmentList()
})
</script>

<style lang="scss" scoped>
.wash-appointment {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 